/* Copyright(c) 2010- Siro-info Co.(http://www.siro-info.com)
 * All rights reserved.
 */
package com.siro.pm.ui.detail;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.siro.pm.Constants;
import com.siro.pm.I18nManager;
import com.siro.pm.model.Document;
import com.siro.pm.model.Project;
import com.siro.pm.model.provider.DocumentProvider;
import com.siro.pm.ui.main.DocumentsPage;
import com.siro.pm.utils.UUIDGenerator;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.ProgressIndicator;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Upload;
import com.vaadin.ui.Upload.FailedEvent;
import com.vaadin.ui.Upload.FinishedEvent;
import com.vaadin.ui.Upload.Receiver;
import com.vaadin.ui.Upload.StartedEvent;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

/**
 * Class Declaration:
 * 
 * @version v1.0
 * @since DocumentDetailPage.java v1.0
 */
public class DocumentDetailPage extends VerticalLayout {
	private static final long serialVersionUID = 6040248825030063945L;
	private static final Logger logger = LoggerFactory
			.getLogger(DocumentDetailPage.class);

	private Window window;
	private DocumentsPage documentsPage;
	private Project ownerProject;
	private File projectFile;
	private File uploadFile;

	private TextField name;
	private TextField project;
	private TextField path;
	private Button button_Save;

	private ProgressIndicator pi = new ProgressIndicator();
	private UploadReceiver receiver = new UploadReceiver();
	private Upload upload;

	public DocumentDetailPage() {
	}

	public DocumentDetailPage(Project ownerProject) {
		this.ownerProject = ownerProject;
	}

	public void createContents() {
		setMargin(true);
		setSpacing(true);

		// base info
		GridLayout documentBaseInfo = new GridLayout();
		documentBaseInfo.setStyleName("h2");
		documentBaseInfo.setCaption(I18nManager
				.getMessage("document.base.info"));
		// documentBaseInfo.setColumns(1);
		documentBaseInfo.setMargin(true);
		documentBaseInfo.setSpacing(true);
		documentBaseInfo.setWidth("100%");

		name = new TextField(DocumentProvider.DOCUMENT_PROPERTY_NAME);
		name.setWidth("100%");
		documentBaseInfo.addComponent(name);

		project = new TextField(DocumentProvider.DOCUMENT_PROPERTY_PROJECT);
		project.setWidth("100%");
		documentBaseInfo.addComponent(project);

		HorizontalLayout pathLayout = new HorizontalLayout();
		pathLayout.setWidth("100%");
		path = new TextField(DocumentProvider.DOCUMENT_PROPERTY_PATH);
		path.setWidth("100%");
		pathLayout.addComponent(path);
		pathLayout.setExpandRatio(path, 1);
		upload = new Upload(" ", receiver);
		upload.setImmediate(true);
		upload.setButtonCaption(I18nManager.getMessage("button.browse"));
		configUpload(upload);
		pathLayout.addComponent(upload);
		documentBaseInfo.addComponent(pathLayout);

		HorizontalLayout progressLayout = new HorizontalLayout();
		progressLayout.setSpacing(true);
		progressLayout.setVisible(false);
		progressLayout.addComponent(pi);
		progressLayout.setComponentAlignment(pi, Alignment.MIDDLE_LEFT);
		documentBaseInfo.addComponent(progressLayout);

		// buttons
		HorizontalLayout buttons = new HorizontalLayout();
		buttons.setMargin(true);
		buttons.setSpacing(true);
		buttons.setWidth("100%");

		button_Save = new Button(I18nManager.getMessage("button.save"));
		button_Save.setWidth(50, Sizeable.UNITS_PIXELS);
		button_Save.addListener(new SaveClickListener());
		buttons.addComponent(button_Save);
		buttons.setComponentAlignment(button_Save, Alignment.MIDDLE_RIGHT);

		addComponent(documentBaseInfo);
		addComponent(buttons);
		initData();
	}

	private void initData() {
		project.setValue(ownerProject.getName());
		project.setEnabled(false);
		String projectDocPath = ownerProject.getName().replaceAll(" ", "_");
		projectDocPath = Constants.DOCUEMNT_ROOT_PATH + projectDocPath;
		try {
			URL path = new URL(projectDocPath);
			projectFile = new File(path.getFile());
			if (!projectFile.exists()) {
				boolean succ = projectFile.mkdirs();
				if (succ) {
					logger.debug("创建项目文档目录" + path.getFile() + "成功");
				}
			}
		} catch (MalformedURLException e) {
			logger.error(e.getMessage(), e);
		}

	}

	private void configUpload(Upload upload2) {
		upload.addListener(new Upload.StartedListener() {
			private static final long serialVersionUID = 1L;

			public void uploadStarted(StartedEvent event) {
				upload.setEnabled(false);
				pi.setValue(0f);
				pi.setPollingInterval(500);
			}
		});

		upload.addListener(new Upload.ProgressListener() {
			private static final long serialVersionUID = 1L;

			public void updateProgress(long readBytes, long contentLength) {
				pi.setValue(new Float(readBytes / (float) contentLength));
			}

		});

		upload.addListener(new Upload.SucceededListener() {
			private static final long serialVersionUID = 1L;

			public void uploadSucceeded(SucceededEvent event) {
				try {
					String canonicalPath = uploadFile.getCanonicalPath();
					int beginIndex = canonicalPath.indexOf("docs");
					path.setValue(canonicalPath.substring(beginIndex));
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		});

		upload.addListener(new Upload.FailedListener() {
			private static final long serialVersionUID = 1L;

			public void uploadFailed(FailedEvent event) {
				path.setValue(I18nManager.getMessage("upload.failed.message")
						+ event.getReason());
			}
		});

		upload.addListener(new Upload.FinishedListener() {
			private static final long serialVersionUID = 1L;

			public void uploadFinished(FinishedEvent event) {
				upload.setEnabled(true);
			}
		});

	}

	class UploadReceiver implements Receiver {
		private static final long serialVersionUID = 5297636587748660014L;

		private String fileName;
		private String mtype;

		public OutputStream receiveUpload(String filename, String mimetype) {
			fileName = filename;
			mtype = mimetype;
			FileOutputStream fos = null;
			try {
				uploadFile = new File(projectFile.getCanonicalPath()
						+ File.separator + filename);
				fos = new FileOutputStream(uploadFile);
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				return null;
			}
			return fos;
		}

		public String getFileName() {
			return fileName;
		}

		public String getMimeType() {
			return mtype;
		}

	}

	class SaveClickListener implements ClickListener {
		private static final long serialVersionUID = -2851840644753744125L;

		public void buttonClick(ClickEvent event) {
			Document doc = new Document();
			doc.setId(UUIDGenerator.newUUID());
			doc.setName((String) name.getValue());
			doc.setProject(ownerProject);
			doc.setPath((String) path.getValue());
			Document.insertDocument(doc);
			// ownerProject.getDocs().add(doc);
			documentsPage.documentsTable
					.setContainerDataSource(DocumentProvider
							.getDocumentsData(documentsPage.getProject()
									.getDocs()));
			(window.getParent()).removeWindow(window);
		}
	}

	public Window getDcocumentWindow() {
		return window;
	}

	public void setWindow(Window window) {
		this.window = window;
	}

	public DocumentsPage getDocumentsPage() {
		return documentsPage;
	}

	public void setDocumentsPage(DocumentsPage documentsPage) {
		this.documentsPage = documentsPage;
	}

	public Project getOwnerProject() {
		return ownerProject;
	}

	public void setOwnerProject(Project ownerProject) {
		this.ownerProject = ownerProject;
	}
}
